const { series, parallel, src, dest, watch } = require('gulp')
// const gulp = require('gulp')
const gulpServer = require('gulp-webserver')
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const webpackStream = require('webpack-stream')
const path = require('path');


function copyHtml() {
  return src('./src/views/*.html')
    .pipe(dest('./dev/'))
}



//编译css
function compileCSS() {
  return src('./src/style/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('all.css'))
    .pipe(dest('./dev/style/'))
}

//编译js
function compileJS() {
  // return src('./src/js/**/*.js')
  //   .pipe(dest('./dev/js/'))
  return src('./src/js/index.js')
    .pipe(webpackStream({
      mode: 'development',
      devtool: 'inline-source-map',
      entry: './src/js/index.js',
      output: {
        //目录
        path: path.resolve(__dirname, './dev/js/'),
        //文件名,
        filename: 'all.js'
      },
      module: {
        rules: [
          // the 'transform-runtime' plugin tells Babel to
          // require the runtime instead of inlining it.
          {
            //匹配js文件
            test: /\.js$/,
            //排除文件
            exclude: /(node_modules)/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
                plugins: ['@babel/plugin-transform-runtime']
              }
            }
          }
        ]
      }
    }))
    .pipe(dest('./dev/js/'))
}

function startServer() {
  return src('./dev/')
    .pipe(gulpServer({
      port: 9090,
      host: '0.0.0.0',
      //是否支持热更新
      livereload: true,
      //是否展示文件夹列表
      //directoryListing: true,
      //打开浏览器
      open: true
    }))
}


//监控文件的变化，当文件有变化时，同步到dev目录
function watchFile() {
  watch('./src/**/*.js', (cb) => {
    console.log('compile js')
    compileJS();
    cb();
  })

  watch('./src/style/*.scss', (cb) => {
    compileCSS();
    cb();
  })


  watch('./src/views/*.html', (cb) => {
    copyHtml();
    cb();
  })
}

exports.default = series(parallel(copyHtml, compileJS, compileCSS), startServer, watchFile);